package sshclient

import (
	"fmt"
	"io/ioutil"
	"log"
	"time"

	"github.com/mitchellh/go-homedir"
	"golang.org/x/crypto/ssh"
)

// 远程主机信息类
type RemoteHostInfo struct {
	Sshhost     string
	Sshuser     string
	Sshpassword string
	Sshtype     string
	Sshkeypath  string
	Sshport     int
}

// ssh 认证为秘钥类型的连接方式
func (RemoteHostInfo) publicKeyAuthFunc(kPath string) ssh.AuthMethod {
	keyPath, err := homedir.Expand(kPath)
	if err != nil {
		log.Fatal("find key's home dir failed", err)
	}
	key, err := ioutil.ReadFile(keyPath)
	if err != nil {
		log.Fatal("ssh key file read failed", err)
	}
	// Create the Signer for this private key.
	signer, err := ssh.ParsePrivateKey(key)
	if err != nil {
		log.Fatal("ssh key signer failed", err)
	}
	return ssh.PublicKeys(signer)
}

// 运行 shell 命令的方法
func (r *RemoteHostInfo) RunScript(shellScript string) {
	//创建sshp登陆配置
	config := &ssh.ClientConfig{
		Timeout:         time.Second * 10, //ssh 连接time out 时间一秒钟, 如果ssh验证错误 会在一秒内返回
		User:            r.Sshuser,
		HostKeyCallback: ssh.InsecureIgnoreHostKey(), //这个可以， 但是不够安全
		//HostKeyCallback: hostKeyCallBackFunc(h.Host),
	}
	if r.Sshtype == "password" {
		config.Auth = []ssh.AuthMethod{ssh.Password(r.Sshpassword)}
	} else {
		config.Auth = []ssh.AuthMethod{r.publicKeyAuthFunc(r.Sshkeypath)}
	}

	//dial 获取ssh client
	addr := fmt.Sprintf("%s:%d", r.Sshhost, r.Sshport)
	sshClient, err := ssh.Dial("tcp", addr, config)
	if err != nil {
		log.Fatal("创建ssh client 失败：", err)
	}
	defer sshClient.Close()

	//创建ssh-session
	session, err := sshClient.NewSession()
	if err != nil {
		log.Fatal("创建ssh session 失败：", err)
	}

	defer session.Close()

	//执行远程命令
	//combo, err := session.CombinedOutput(shellScript)
	_, err = session.CombinedOutput(shellScript)
	if err != nil {
		log.Fatal("远程执行cmd 失败：", shellScript, err)
	}
	//log.Println("命令输出:", string(combo))
}